package com.mrjy.common.controller;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.mrjy.common.bo.IPaymentBo;
import com.mrjy.common.entity.OrderInfo;
import com.mrjy.common.entity.TransferInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.maintain.bo.IUserInfoBo;
import com.mrjy.payment.bo.IUserBalancePaymentBo;
import com.mrjy.wechat.conts.WxConsts;
import com.tencent.common.Configure;
import com.tencent.common.Log;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;
import com.tencent.common.Util;
import com.tencent.protocol.pay_protocol.OAuthReqData;
import com.tencent.protocol.pay_protocol.ScanPayReqData;
import com.tencent.protocol.pay_protocol.ScanPayResData;
import com.tencent.protocol.pay_protocol.TransferPayReqData;
import com.tencent.protocol.pay_protocol.TransferPayResData;
import com.tencent.service.ScanPayService;
import com.tencent.service.TransferPayService;

@Controller
@RequestMapping("common/payment")
public class IPaymentController {
	
	@Resource
	private IUserInfoBo userInfoBo; 
	
	@Resource
	private IUserBalancePaymentBo userBalancePaymentBo;
	

	// 打log用
	private static Log log = new Log(LoggerFactory.getLogger(IPaymentController.class));
	
	/**
	 * 支付宝页面跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/alipayapi")
	public String alipayapi(HttpServletRequest request,HttpSession session) throws Exception {
        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //商户网站订单系统中唯一订单号，必填
        
        String className = request.getParameter("className");
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(className);
        OrderInfo orderInfo = paymentBo.selectWaitingByCode(out_trade_no);
        if (orderInfo==null || "fail".equals(orderInfo.getMessageString())) {
        	return "payment/alipayapi";
		}
        
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//        	userInfo = userInfoBo.queryById(orderInfo.getUserId());
//		}
        if (userInfo==null) {
        	return "payment/alipayapi";
		}
        
        String systemBasePath = WxConsts.PUBLIC_DOMAIN + request.getContextPath() + "/";
        //支付类型
        String payment_type = "1";
        //必填，不能修改
        //服务器异步通知页面路径
        String notify_url = systemBasePath + request.getParameter("notify_url");
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        String return_url = systemBasePath + request.getParameter("return_url");
        
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
        
        //订单名称
        String subject = orderInfo.getName();
        //必填
        //付款金额
        String total_fee = orderInfo.getMoney()+"";
        //必填
        //支付方式
        String paytype = request.getParameter("paytype");
        //默认支付方式
        String paymethod = "bankPay";
        //防钓鱼时间戳
        String anti_phishing_key = AlipaySubmit.query_timestamp();
        //若要使用请调用类文件submit中的query_timestamp函数
        //取客户端真实的IP地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户ip   
        if (ip != null && ip.indexOf(",") != -1) {  
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();  
        } 
        //客户端的IP地址
        String exter_invoke_ip = ip;
        System.out.println("客户端外网ip:"+exter_invoke_ip);
        //非局域网的外网IP地址，如：221.0.0.1
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_email", AlipayConfig.seller_email);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", payment_type);
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("return_url", return_url);
        sParaTemp.put("out_trade_no", out_trade_no);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        if(!"alipay".equals(paytype)){
           sParaTemp.put("paymethod", paymethod);
           sParaTemp.put("defaultbank", paytype);
        }
        sParaTemp.put("anti_phishing_key", anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
        //建立请求
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
        request.setAttribute("sHtmlText", sHtmlText);
        return "payment/alipayapi";
	}
	

	
	
	/**
	 * wap支付宝页面跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/alipayapiwap")
	public String alipayapiwap(HttpServletRequest request,HttpSession session) throws Exception {
        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //商户网站订单系统中唯一订单号，必填
        
        String className = request.getParameter("className");
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(className);
        OrderInfo orderInfo = paymentBo.selectWaitingByCode(out_trade_no);
        if (orderInfo==null || "fail".equals(orderInfo.getMessageString()) || "fail".equals(orderInfo)) {
        	return "payment/alipayapi";
		}
        
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (userInfo == null && orderInfo.getUserId() != null) {
        	userInfo = userInfoBo.queryById(orderInfo.getUserId());
		}
        if (userInfo==null) {
        	return "payment/alipayapi";
		}
        
        String systemBasePath = WxConsts.PUBLIC_DOMAIN + request.getContextPath() + "/";
        //支付类型
        String payment_type = "1";
        //wap移动
        String type = request.getParameter("type");
        //必填，不能修改
        //服务器异步通知页面路径
        String notify_url = systemBasePath + request.getParameter("notify_url");
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        String return_url = systemBasePath + request.getParameter("return_url");
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
        
        //订单名称
        String subject = orderInfo.getName();
        //必填
        //付款金额
        String total_fee = orderInfo.getMoney()+"";
        //必填
        //支付方式
        String paytype = request.getParameter("paytype");
        //默认支付方式
        String paymethod = "bankPay";
        //防钓鱼时间戳
        String anti_phishing_key = AlipaySubmit.query_timestamp();
        //若要使用请调用类文件submit中的query_timestamp函数
        //取客户端真实的IP地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户ip   
        if (ip != null && ip.indexOf(",") != -1) {  
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();  
        } 
        //客户端的IP地址
        String exter_invoke_ip = ip;
        System.out.println("客户端外网ip:"+exter_invoke_ip);
        //非局域网的外网IP地址，如：221.0.0.1
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", "alipay.wap.create.direct.pay.by.user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_email);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", payment_type);
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("return_url", return_url+"?type="+type);
        sParaTemp.put("out_trade_no", out_trade_no);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        if(!"alipay".equals(paytype)){
           sParaTemp.put("paymethod", paymethod);
           sParaTemp.put("defaultbank", paytype);
        }
        sParaTemp.put("anti_phishing_key", anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
        //建立请求
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
        request.setAttribute("sHtmlText", sHtmlText);
        return "payment/alipayapi";
	}
	
	
	/**
	 * 发起微信扫码支付统一下单API
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doScanPayBusiness")
	@ResponseBody
	public Object doScanPayBusiness(HttpServletRequest request, HttpSession session, OrderInfo orderInfo) throws Exception {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(orderInfo.getClassName());
		OrderInfo orderInfoCheck = paymentBo.doScanPayBusiness(orderInfo.getCode());
		if (orderInfoCheck == null || "fail".equals(orderInfoCheck.getMessageString()) || "fail".equals(orderInfoCheck)) {
			return orderInfoCheck;
		}
		
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (userInfo == null) {
        	userInfo = userInfoBo.queryById(orderInfoCheck.getUserId());
		}
        if (userInfo==null) {
        	orderInfoCheck.setMessageString("fail");
        	return orderInfoCheck;
		}
		// 构造请求“被扫支付API”所需要提交的数据
		ScanPayReqData scanPayReqData = new ScanPayReqData();
		scanPayReqData.setAppid(Configure.getAppid());
		scanPayReqData.setMch_id(Configure.getMchid());
		scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		scanPayReqData.setBody(orderInfoCheck.getName());
		scanPayReqData.setOut_trade_no(orderInfoCheck.getCode());
		scanPayReqData.setTotal_fee(Integer.parseInt(Util.getMoney(orderInfoCheck.getMoney() + "")));
		InetAddress netAddress = Util.getInetAddress();
		scanPayReqData.setSpbill_create_ip(Util.getHostIp(netAddress));
//		String systemBasePath = "http://" +  "114.55.29.21:83" + request.getContextPath() + "/"; 
		String systemBasePath = WxConsts.PUBLIC_DOMAIN + request.getContextPath() + "/";
		String notify_url = systemBasePath + orderInfo.getWxnotify_url();
		scanPayReqData.setNotify_url(notify_url);
		scanPayReqData.setTrade_type("NATIVE");
//		scanPayReqData.setProduct_id(orderInfoCheck.getArrangementId() + "");
		scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
		// 接受API返回结果
		String payServiceResponseString;
		long costTimeStart = System.currentTimeMillis();
		ScanPayService scanPayService = new ScanPayService();
		//log.i("支付API返回的数据如下：");
		payServiceResponseString = scanPayService.request(scanPayReqData);
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		//log.i("api请求总耗时：" + totalTimeCost + "ms");
		// 打印回包数据
		//log.i(payServiceResponseString);
		// 将从API返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(payServiceResponseString, ScanPayResData.class);
		if ("SUCCESS".equals(scanPayResData.getReturn_code())
				&& "OK".equals(scanPayResData.getReturn_msg())) {
			if("SUCCESS".equals(scanPayResData.getResult_code())){
				orderInfoCheck.setCode_url(scanPayResData.getCode_url());
				orderInfoCheck.setMessageString("success");
			}else {
				orderInfoCheck.setMessageString("fail");
			}
		} else {
			orderInfoCheck.setMessageString("fail");
		}
		return orderInfoCheck;
	}
	
	
	/**
	 * 公众号发起微信支付统一下单API
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/weixinPayBusiness")
	@ResponseBody
	public Object weixinPayBusiness(HttpServletRequest request, HttpSession session, OrderInfo orderInfo, String openid) throws Exception {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(orderInfo.getClassName());
        OrderInfo orderInfoCheck = paymentBo.doScanPayBusiness(orderInfo.getCode());
		
		if ("fail".equals(orderInfoCheck.getMessageString())) {
			return orderInfoCheck;
		}
		
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        /*if (userInfo == null) {
        	userInfo = userInfoBo.queryById(orderInfo.getUserId());
		}*/
        if (userInfo==null) {
        	orderInfoCheck.setMessageString("fail");
//        	jsonp(request, response, orderInfoCheck);
        	return orderInfoCheck;
		}
		ScanPayReqData scanPayReqData = new ScanPayReqData();
		scanPayReqData.setAppid(Configure.getAppid());
		scanPayReqData.setMch_id(Configure.getMchid());
//		scanPayReqData.setDevice_info("WEB");
		scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		System.out.println(orderInfoCheck.getName());
		scanPayReqData.setBody(orderInfoCheck.getName());
		scanPayReqData.setOut_trade_no(orderInfoCheck.getCode());
		scanPayReqData.setTotal_fee(Integer.parseInt(Util.getMoney(orderInfoCheck.getMoney() + "")));
		InetAddress netAddress = Util.getInetAddress();
		scanPayReqData.setSpbill_create_ip(Util.getHostIp(netAddress));
		
		String systemBasePath = WxConsts.PUBLIC_DOMAIN + "/mrjy";
		
		String notify_url = systemBasePath + orderInfo.getWxnotify_url();
		scanPayReqData.setNotify_url(notify_url);
		scanPayReqData.setTrade_type("JSAPI");
		scanPayReqData.setOpenid(openid);
		scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
		
//		return scanPayReqData;
		// 接受API返回结果
		String payServiceResponseString;
		long costTimeStart = System.currentTimeMillis();
		ScanPayService scanPayService = new ScanPayService();
		log.i("支付API返回的数据如下：");
		payServiceResponseString = scanPayService.request(scanPayReqData);
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		log.i("api请求总耗时：" + totalTimeCost + "ms");
		// 打印回包数据
		log.i(payServiceResponseString);
		orderInfoCheck.setLogData(payServiceResponseString);
		// 将从API返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(payServiceResponseString, ScanPayResData.class);
		if ("SUCCESS".equals(scanPayResData.getReturn_code())
				&& "OK".equals(scanPayResData.getReturn_msg())) {
			if("SUCCESS".equals(scanPayResData.getResult_code())){
				Map<String, Object> jsApiMap = new HashMap<String, Object>();
				jsApiMap.put("appId", scanPayResData.getAppid());
				String timeStamp = Long.toString(new Date().getTime());
				jsApiMap.put("timeStamp", timeStamp);
				jsApiMap.put("nonceStr", scanPayResData.getNonce_str());
				String packageStr = "prepay_id=" + scanPayResData.getPrepay_id();
				jsApiMap.put("package", packageStr);
				jsApiMap.put("signType", "MD5");
				
//				String paySign = MD5.MD5Encode("appid=" + scanPayResData.getAppid() + "&nonceStr=" + scanPayResData.getNonce_str()
//						+ "&package=" + packageStr + "&signType=MD5" + "&timeStamp=" + timeStamp + "&key=" + Configure.getKey()).toUpperCase();
				String paySign = Signature.getSign(jsApiMap);
				jsApiMap.put("paySign", paySign);
				jsApiMap.put("messageString", "success");
				return jsApiMap;
//				jsonp(request, response, jsApiMap);
			}else {
				orderInfoCheck.setMessageString("fail");
			}
		} else {
			orderInfoCheck.setMessageString("fail");
		}
//		jsonp(request, response, orderInfoCheck);
		return orderInfoCheck;
	}
	
	/**
	 * WEB H5 发起支付统一下单API
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/weixinPayBusinessByH5")
	@ResponseBody
	public Object weixinPayBusinessByH5(HttpServletRequest request, HttpSession session, OrderInfo orderInfo, String openid) throws Exception {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(orderInfo.getClassName());
        OrderInfo orderInfoCheck = paymentBo.doScanPayBusiness(orderInfo.getCode());
		if ("fail".equals(orderInfoCheck.getMessageString())) {
			return orderInfoCheck;
		}
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (userInfo==null) {
        	orderInfoCheck.setMessageString("fail");
        	return orderInfoCheck;
		}
		ScanPayReqData scanPayReqData = new ScanPayReqData();
		scanPayReqData.setAppid(Configure.getAppid());
		scanPayReqData.setMch_id(Configure.getMchid());
		scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		System.out.println(orderInfoCheck.getName());
		scanPayReqData.setBody(orderInfoCheck.getName());
		scanPayReqData.setOut_trade_no(orderInfoCheck.getCode());
		scanPayReqData.setTotal_fee(Integer.parseInt(Util.getMoney(orderInfoCheck.getMoney() + "")));
//		InetAddress netAddress = Util.getInetAddress();
		scanPayReqData.setSpbill_create_ip(Util.getIpAddr(request));
		
		String systemBasePath = WxConsts.PUBLIC_DOMAIN + "/mrjy";
		
		String notify_url = systemBasePath + orderInfo.getWxnotify_url();
		scanPayReqData.setNotify_url(notify_url);
		scanPayReqData.setTrade_type("MWEB");
		scanPayReqData.setOpenid(openid);
		scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
		
//		return scanPayReqData;
		// 接受API返回结果
		String payServiceResponseString;
		long costTimeStart = System.currentTimeMillis();
		ScanPayService scanPayService = new ScanPayService();
		log.i("支付API返回的数据如下：");
		payServiceResponseString = scanPayService.request(scanPayReqData);
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		log.i("api请求总耗时：" + totalTimeCost + "ms");
		// 打印回包数据
		log.i("===>"+payServiceResponseString);
		orderInfoCheck.setLogData(payServiceResponseString);
		// 将从API返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(payServiceResponseString, ScanPayResData.class);
		if ("SUCCESS".equals(scanPayResData.getReturn_code())
				&& "OK".equals(scanPayResData.getReturn_msg())) {
			if("SUCCESS".equals(scanPayResData.getResult_code())){
				Map<String, Object> jsApiMap = new HashMap<String, Object>();
				jsApiMap.put("messageString", "success");
				jsApiMap.put("mweb_url", scanPayResData.getMweb_url());
				return jsApiMap;
			}else {
				orderInfoCheck.setMessageString("fail");
			}
		} else {
			orderInfoCheck.setMessageString("fail");
		}
		return orderInfoCheck;
	}
	
	/**
	 * 小程序发起微信支付统一下单API
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/miniProgramPayBusiness")
	@ResponseBody
	public Object miniProgramPayBusiness(HttpServletRequest request, HttpSession session, OrderInfo orderInfo, String openid) throws Exception {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        IPaymentBo paymentBo = (IPaymentBo)wac.getBean(orderInfo.getClassName());
        OrderInfo orderInfoCheck = paymentBo.doScanPayBusiness(orderInfo.getCode());
		
		if ("fail".equals(orderInfoCheck.getMessageString())) {
			return orderInfoCheck;
		}
		
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        /*if (userInfo == null) {
        	userInfo = userInfoBo.queryById(orderInfo.getUserId());
		}*/
        if (userInfo==null) {
        	orderInfoCheck.setMessageString("fail");
//        	jsonp(request, response, orderInfoCheck);
        	return orderInfoCheck;
		}
		ScanPayReqData scanPayReqData = new ScanPayReqData();
		scanPayReqData.setAppid(Configure.getMiniAppId());
		scanPayReqData.setMch_id(Configure.getMchid());
//		scanPayReqData.setDevice_info("WEB");
		scanPayReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		System.out.println(orderInfoCheck.getName());
		scanPayReqData.setBody(orderInfoCheck.getName());
		scanPayReqData.setOut_trade_no(orderInfoCheck.getCode());
		scanPayReqData.setTotal_fee(Integer.parseInt(Util.getMoney(orderInfoCheck.getMoney() + "")));
		InetAddress netAddress = Util.getInetAddress();
		scanPayReqData.setSpbill_create_ip(Util.getHostIp(netAddress));
		
		String systemBasePath = WxConsts.PUBLIC_DOMAIN + "/mrjy";
		
		String notify_url = systemBasePath + orderInfo.getWxnotify_url();
		scanPayReqData.setNotify_url(notify_url);
		scanPayReqData.setTrade_type("JSAPI");
		scanPayReqData.setOpenid(openid);
		scanPayReqData.setSign(Signature.getSign(scanPayReqData.toMap()));
		
//		return scanPayReqData;
		// 接受API返回结果
		String payServiceResponseString;
		long costTimeStart = System.currentTimeMillis();
		ScanPayService scanPayService = new ScanPayService();
		log.i("支付API返回的数据如下：");
		payServiceResponseString = scanPayService.request(scanPayReqData);
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		log.i("api请求总耗时：" + totalTimeCost + "ms");
		// 打印回包数据
		log.i(payServiceResponseString);
		orderInfoCheck.setLogData(payServiceResponseString);
		// 将从API返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(payServiceResponseString, ScanPayResData.class);
		if ("SUCCESS".equals(scanPayResData.getReturn_code())
				&& "OK".equals(scanPayResData.getReturn_msg())) {
			if("SUCCESS".equals(scanPayResData.getResult_code())){
				Map<String, Object> jsApiMap = new HashMap<String, Object>();
				jsApiMap.put("appId", scanPayResData.getAppid());
				String timeStamp = Long.toString(new Date().getTime());
				jsApiMap.put("timeStamp", timeStamp);
				jsApiMap.put("nonceStr", scanPayResData.getNonce_str());
				String packageStr = "prepay_id=" + scanPayResData.getPrepay_id();
				jsApiMap.put("package", packageStr);
				jsApiMap.put("signType", "MD5");
				
//				String paySign = MD5.MD5Encode("appid=" + scanPayResData.getAppid() + "&nonceStr=" + scanPayResData.getNonce_str()
//						+ "&package=" + packageStr + "&signType=MD5" + "&timeStamp=" + timeStamp + "&key=" + Configure.getKey()).toUpperCase();
				String paySign = Signature.getSign(jsApiMap);
				jsApiMap.put("paySign", paySign);
				jsApiMap.put("messageString", "success");
				return jsApiMap;
//				jsonp(request, response, jsApiMap);
			}else {
				orderInfoCheck.setMessageString("fail");
			}
		} else {
			orderInfoCheck.setMessageString("fail");
		}
//		jsonp(request, response, orderInfoCheck);
		return orderInfoCheck;
	}
	
	/**
	 * 企业付款至用户
	 * @param request
	 * @param session
	 * @param tranInfo
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/weChatTransferPay")
	@ResponseBody
	public Object weChatTransferPay(HttpServletRequest request, HttpSession session, TransferInfo tranInfo, String openid) throws Exception{
		TransferPayReqData reqData = new TransferPayReqData();
		reqData.setMch_appid(Configure.getAppid());
		reqData.setMchid(Configure.getMchid());
		reqData.setDevice_info("");
		reqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
		reqData.setPartner_trade_no(tranInfo.getPartnerTradeNo());
		reqData.setOpenid(openid);
		reqData.setCheck_name("NO_CHECK");
		reqData.setRe_user_name("");
		reqData.setAmount(Integer.parseInt(Util.getMoney(tranInfo.getAmount() + "")));
		reqData.setDesc(tranInfo.getPaymentDesc());
		reqData.setSpbill_create_ip(Util.getHostIp(Util.getInetAddress()));
		reqData.setSign(Signature.getSign(reqData.toMap()));
		TransferPayService payService = null;
		String payServiceResponseString;
		long costTimeStart = System.currentTimeMillis();
		log.i("支付API返回的数据如下：");
		payService = new TransferPayService();
		payServiceResponseString = payService.request(reqData);
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		log.i("api请求总耗时：" + totalTimeCost + "ms");
		log.i(payServiceResponseString);
		
		TransferPayResData transferPayResData = (TransferPayResData) Util.getObjectFromXML(payServiceResponseString, TransferPayResData.class);
		if ("SUCCESS".equals(transferPayResData.getReturn_code())
			&& "SUCCESS".equals(transferPayResData.getResult_code())) {
				Map<String, Object> jsApiMap = new HashMap<String, Object>();
				jsApiMap.put("mchAppid", transferPayResData.getMch_appid());
				jsApiMap.put("mchId", transferPayResData.getMchid());
				String timeStamp = Long.toString(new Date().getTime());
				jsApiMap.put("timeStamp", timeStamp);
				jsApiMap.put("nonceStr", transferPayResData.getNonce_str());
				jsApiMap.put("signType", "MD5");
				if("SUCCESS".equals(transferPayResData.getResult_code())){
					jsApiMap.put("partnerTradeNo", transferPayResData.getPartner_trade_no());
					jsApiMap.put("paymentNo", transferPayResData.getPayment_no());
					jsApiMap.put("paymentTime", transferPayResData.getPayment_time());
				}
				
				String paySign = Signature.getSign(jsApiMap);
				jsApiMap.put("paySign", paySign);
				jsApiMap.put("messageString", "success");
				return jsApiMap;
		} else {
			tranInfo.setMessageString("fail");
		}
		
		return tranInfo;
	}
	
	/**
	 * 授权获取openid
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getOpenid")
	@ResponseBody
	public Object getOpenid(HttpServletRequest request, HttpServletResponse response, HttpSession session, OAuthReqData oAuthReqData) throws Exception {
		HttpClient httpClient = new DefaultHttpClient(); 
        HttpPost httpPost = new HttpPost(Configure.OAUTH_API);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        nvps.add(new BasicNameValuePair("appid", Configure.getAppid()));  
        nvps.add(new BasicNameValuePair("secret", Configure.getSecret()));
        /**
         * 测试账号
         * @author Javin
         */
//        nvps.add(new BasicNameValuePair("appid", WxConsts.APPID));  
//        nvps.add(new BasicNameValuePair("secret", WxConsts.APPSECRET));
        nvps.add(new BasicNameValuePair("code", oAuthReqData.getCode()));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        
        httpPost.setEntity(new UrlEncodedFormEntity(nvps)); 
        
        long costTimeStart = System.currentTimeMillis();
        HttpResponse clientRes = httpClient.execute(httpPost);
        HttpEntity entity = clientRes.getEntity();
        String getOAuthResponseString = EntityUtils.toString(entity, "UTF-8");
		long costTimeEnd = System.currentTimeMillis();
		long totalTimeCost = costTimeEnd - costTimeStart;
		
		System.out.println("--" + totalTimeCost);
		System.out.println("--" + getOAuthResponseString);
		// 将从API返回的XML数据映射到Java对象
		return getOAuthResponseString;
//		jsonp(request, response, getOAuthResponseString);
	}
	/**
	 * @author Javin
	 * @date 2017年7月24日
	 * @desc 获取生成扫码支付二维码URL
	 * @param info
	 * @return
	 */
	@RequestMapping("/getScanPayUrl")
	@ResponseBody
	public Object getScanPayUrl(OrderInfo info){
		return userBalancePaymentBo.getScanPayUrl(info);
	}
	
	/**
	 * 
	 * @author Javin
	 * @date 2017年7月24日
	 * @desc 扫码支付回调URL
	 * @param request
	 * @return
	 */
	@RequestMapping("/scanPayReturnUrl")
	@ResponseBody
	public Object scanPayReturnUrl(HttpServletRequest request){
		Map<String, String[]> map = request.getParameterMap();
		return map;
	}
	
}
